/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.yczbj.ycvideoplayer.utils;

import ohos.agp.components.Image;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Rect;
import ohos.media.image.common.Size;

import com.yc.music.utils.MusicLogUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 异步加载图片
 *
 * @since 2021-05-12
 */
public class ImageLoader {
    /**
     * loadImage
     *
     * @param context context
     * @param path path
     * @param thumb thumb
     */
    public static void loadImage(Context context, String path, Image thumb) {
        TaskDispatcher refreshUiTask = context.createParallelTaskDispatcher("", TaskPriority.HIGH);
        TaskDispatcher uiTaskDispatcher = context.getUITaskDispatcher();
        refreshUiTask.asyncDispatch(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(path);
                    URLConnection urlConnection = url.openConnection();
                    if (urlConnection instanceof HttpURLConnection) {
                        connection = (HttpURLConnection) urlConnection;
                    }
                    if (connection != null) {
                        connection.connect();
                        InputStream inputStream = urlConnection.getInputStream();
                        ImageSource imageSource = ImageSource.create(inputStream, new ImageSource.SourceOptions());
                        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                        decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
                        PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);

                        uiTaskDispatcher.asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                thumb.setScaleMode(Image.ScaleMode.CLIP_CENTER);
                                thumb.setPixelMap(pixelMap);
                                pixelMap.release();
                            }
                        });
                        if (inputStream != null) {
                            inputStream.close();
                        }
                    }
                } catch (IOException e) {
                    MusicLogUtils.e(e.getMessage());
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        });
    }

    /**
     * 加载本地图片
     *
     * @param context context
     * @param resId resId
     * @param image image
     */
    public static void loadImage(Context context, int resId, Image image) {
        InputStream drawableInputStream = null;
        try {
            drawableInputStream = context.getResourceManager().getResource(resId);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = "image/jpg/png";
            final ImageSource imageSource = ImageSource.create(drawableInputStream, null);
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredSize = new Size(0, 0);
            decodingOptions.desiredRegion = new Rect(0, 0, 0, 0);
            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
            image.setPixelMap(pixelMap);
        } catch (Exception e) {
            MusicLogUtils.e(e.getMessage());
        } finally {
            try {
                if (drawableInputStream != null) {
                    drawableInputStream.close();
                }
            } catch (Exception e) {
                MusicLogUtils.e(e.getMessage());
            }
        }
    }
}
